package com.thedeveloperworldisyours.fullrecycleview.swipe.adapter;

import com.demo.swipe.RippleUtil;
import com.demo.swipe.SwipeLayout;

import com.thedeveloperworldisyours.fullrecycleview.ResourceTable;
import com.thedeveloperworldisyours.fullrecycleview.swipe.Employee;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.TextAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;

import java.util.ArrayList;
import java.util.function.Consumer;

/**
 * Created by javierg on 12/10/2016.
 */

public   class SwipeRecyclerViewAdapter extends BaseItemProvider {

    private Context mContext;
    private LayoutScatter scatter;
    private ArrayList<Employee> studentList;

    public SwipeRecyclerViewAdapter(Context context, LayoutScatter scatter, ArrayList<Employee> objects) {
        this.mContext = context;
        this.scatter = scatter;
        this.studentList = objects;
    }

    public int getSwipeLayoutResourceId(int position) {
        return ResourceTable.Id_swipe;
    }

    @Override
    public int getCount() {
        return studentList == null || studentList.size() == 0 ? 0 : studentList.size();
    }

    @Override
    public Employee getItem(int position) {
        return studentList.get(position);
    }

    @Override
    public long getItemId(int id) {
        return 0;
    }

    @Override
    public Component getComponent(int position, Component component, ComponentContainer componentContainer) {
        final Employee item = studentList.get(position);
        SimpleViewHolder simpleViewHolder;
        if (component == null) {
            component = scatter.parse(ResourceTable.Layout_swipe_list_item, componentContainer, false);
            simpleViewHolder = new SimpleViewHolder(component);
            component.setTag(simpleViewHolder);
        } else {
            simpleViewHolder = (SimpleViewHolder) component.getTag();
        }


        simpleViewHolder.swipeLayout.addSwipeListener(new SwipeLayout.SwipeListener() {
            @Override
            public void onClose(SwipeLayout layout) {
                layout.setWillOpenPercentAfterOpen(0.2f);
                item.setDragEdge(null);
            }

            @Override
            public void onUpdate(SwipeLayout layout, int leftOffset, int topOffset) {

            }

            @Override
            public void onStartOpen(SwipeLayout layout) {
                studentList.forEach(new Consumer<Employee>() {
                    @Override
                    public void accept(Employee employee) {
                        if (employee.getDragEdge() != null&&position!=studentList.indexOf(employee)) {
                            employee.setDragEdge(null);
                            notifyDataSetItemChanged(studentList.indexOf(employee));
                        }
                    }
                });
            }

            @Override
            public void onOpen(SwipeLayout layout) {
                layout.setWillOpenPercentAfterOpen(0.85f);
                item.setDragEdge(layout.getDragEdge());
            }

            @Override
            public void onStartClose(SwipeLayout layout) {
            }

            @Override
            public void onHandRelease(SwipeLayout layout, float xvel, float yvel) {
            }
        });
        simpleViewHolder.swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);
        // Drag From Left
        simpleViewHolder.swipeLayout.addDrag(SwipeLayout.DragEdge.Left, simpleViewHolder.swipeLayout.findComponentById(ResourceTable.Id_swipe_item_list_left_bottom_wrapper));

        // Drag From Right
        simpleViewHolder.swipeLayout.addDrag(SwipeLayout.DragEdge.Right, simpleViewHolder.swipeLayout.findComponentById(ResourceTable.Id_item_list_bottom_wrapper));


        if (item.getDragEdge() != null) {
            simpleViewHolder.swipeLayout.open(false, item.getDragEdge());
        } else {
            simpleViewHolder.swipeLayout.close(true, false);
        }

        simpleViewHolder.tvName.setText((item.getName()));
        simpleViewHolder.tvEmailId.setText(item.getEmailId());

        RippleUtil.setComponentClickListener(simpleViewHolder.swipeLayout, 30, Color.getIntColor("#aaaaaa"), simpleViewHolder.swipeLayout, new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                showToast("onClick:" + item.getName());
            }
        });

        simpleViewHolder.tvEdit.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                showToast(item.getName());
            }
        });

        simpleViewHolder.tvDelete.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                int position = studentList.indexOf(item);
                /*int lastVisiblePosition = ((ListContainer) componentContainer).getItemPosByVisibleIndex(((ListContainer) componentContainer).getVisibleIndexCount() - 1);
                if (lastVisiblePosition == getCount() - 1) {
                    //这种情况，就不执行动画，直接删除(notifyDataSetItemChanged方法只能让后面的数据往前补，并不能将前面的数据往后补，导致动画只能让后面的Component向上移动，当到底部后无法正常移动时，会引发listcontainer的重新测量布局）
                    studentList.remove(position);
                    notifyDataSetItemRemoved(position);
                    return;
                }*/
                Component child = componentContainer.getComponentAt(position);
                int height = child.getHeight();
                AnimatorValue animatorValue = new AnimatorValue();
                animatorValue.setDuration(300);
                animatorValue.setValueUpdateListener(new AnimatorValue.ValueUpdateListener() {
                    @Override
                    public void onUpdate(AnimatorValue animatorValue, float value) {
                        float tempHeight = (height * (Float.sum(-value, 1f)));
                        if (tempHeight == 0) {
                            studentList.remove(position);
                            notifyDataSetItemRemoved(position);
                            child.setHeight(height);
                            notifyDataChanged();
                        } else {
                            child.setHeight((int) tempHeight);
                            notifyDataSetItemChanged(position);
                        }
                    }
                });
                animatorValue.start();
            }
        });
        return component;
    }


    public static class SimpleViewHolder {
        SwipeLayout swipeLayout;
        Text tvName;
        Text tvEmailId;
        Text tvDelete;
        Text tvEdit;

        public SimpleViewHolder(Component itemView) {
            swipeLayout = (SwipeLayout) itemView.findComponentById(ResourceTable.Id_swipe);
            tvName = (Text) itemView.findComponentById(ResourceTable.Id_swipe_item_list_text_view_name);
            tvEmailId = (Text) itemView.findComponentById(ResourceTable.Id_swipe_item_list_text_view_email_id);
            tvDelete = (Text) itemView.findComponentById(ResourceTable.Id_swipe_item_list_delete_text_view);
            tvEdit = (Text) itemView.findComponentById(ResourceTable.Id_swipe_item_list_edit_text);
        }
    }

    private void showToast(String msg) {
        ToastDialog toastDialog = new ToastDialog(mContext);

        ShapeElement shapeElement = new ShapeElement();
        RgbColor rgbColor = RgbColor.fromArgbInt(Color.getIntColor("#ff333333"));
        shapeElement.setRgbColor(rgbColor);
        Text text = new Text(mContext);

        text.setLayoutConfig(new StackLayout.LayoutConfig(ComponentContainer.LayoutConfig.MATCH_PARENT,
                ComponentContainer.LayoutConfig.MATCH_CONTENT));
        text.setBackground(shapeElement);
        text.setMultipleLine(true);
        text.setTextSize(48);
        text.setTextAlignment(TextAlignment.LEFT);
        text.setTextColor(Color.WHITE);
        text.setBindStateChangedListener(new Component.BindStateChangedListener() {
            private AnimatorValue showAnimatorValue;

            @Override
            public void onComponentBoundToWindow(Component component) {
                showAnimatorValue = new AnimatorValue();
                showAnimatorValue.setDuration(300);
                showAnimatorValue.setValueUpdateListener((animatorValue, v) -> {
                    component.setAlpha(v);
                    component.setTranslationY(component.getHeight() - (v * component.getHeight()));
                });
                showAnimatorValue.start();

            }

            @Override
            public void onComponentUnboundFromWindow(Component component) {
                if (showAnimatorValue != null) {
                    showAnimatorValue.cancel();
                    showAnimatorValue.release();
                }
            }
        });
        text.setText(msg);
        text.setPadding(60, 30, 50, 30);
        toastDialog.setSize(DisplayManager.getInstance().getDefaultDisplay(mContext).get().getAttributes().width, -2);
        text.setAlpha(0);
        text.setTranslationY(DisplayManager.getInstance().getDefaultDisplay(mContext).get().getAttributes().height);
        toastDialog.setComponent(text);
        toastDialog.show();
    }
}
